import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/hide_scroll_shadow/hide_scroll_shadow.dart';
import 'package:flutter_application_1/utils/utils.dart';

class PayPasswordDialog extends StatefulWidget {
  final Color bgColor;

  PayPasswordDialog({
    this.bgColor = const Color.fromRGBO(246, 246, 246, 1),
  });

  @override
  State<StatefulWidget> createState() => PayPasswordDialogState();
}

class PayPasswordDialogState extends State<PayPasswordDialog> {
  final int _maxLength = 6;

  String _password = '';

  List<String> _passwordList = [];

  List<String> _keyboardList = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '',
    '0',
    'backspace',
  ];

  // 标题
  Widget _titleBuilder() {
    return Stack(
      children: <Widget>[
        Container(
          height: 45,
          decoration: BoxDecoration(
            color: widget.bgColor,
            border: Border(
              bottom: BorderSide(
                width: Utils.rpx,
                color: Color.fromRGBO(213, 213, 213, 1),
              ),
            ),
          ),
        ),
        Positioned.fill(
          child: Container(
            alignment: Alignment.center,
            child: Text(
              '输入支付密码',
              style: TextStyle(
                color: Color.fromRGBO(138, 138, 138, 1),
                fontSize: 16,
              ),
            ),
          ),
        ),
        Positioned(
          left: 0,
          top: 0,
          bottom: 0,
          child: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Icon(
              Icons.chevron_left,
              size: 35,
              color: Color.fromRGBO(153, 153, 153, 0.5),
            ),
          ),
        ),
      ],
    );
  }

  // 单个密码据悉
  Widget _passwordRect({
    isLast: false,
    hasInput: false,
  }) {
    BoxBorder border = Border();
    if (!isLast) {
      border = Border(
        right: BorderSide(
          width: isLast ? 0 : 1 * Utils.rpx,
          color: Color.fromRGBO(213, 213, 213, 1),
        ),
      );
    }
    return Container(
      width: 55,
      height: 50,
      decoration: BoxDecoration(
        border: border,
      ),
      child: Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(30),
          child: Container(
            width: 20,
            height: 20,
            color: hasInput ? Colors.black87 : Colors.transparent,
          ),
        ),
      ),
    );
  }

  // 密码栏
  Widget _passwordRowBuilder() {
    return Container(
      alignment: Alignment.center,
      color: widget.bgColor,
      padding: EdgeInsets.symmetric(
        vertical: 20,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              border: Border.all(
                width: 1 * Utils.rpx,
                color: Color.fromRGBO(213, 213, 213, 1),
              ),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: _passwordList
                  .asMap()
                  .keys
                  .map(
                    (index) => _passwordRect(
                      isLast: index == _passwordList.length - 1,
                      hasInput: _passwordList[index].isNotEmpty,
                    ),
                  )
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }

  // 单个键盘
  Widget _keyboardRect(int index) {
    String keyboardValue = _keyboardList[index];
    if (keyboardValue.isNotEmpty) {
      bool isBackspace = keyboardValue == 'backspace';
      return Stack(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            color: isBackspace ? Colors.transparent : widget.bgColor,
            child: isBackspace
                ? Icon(
                    Icons.backspace,
                  )
                : Text(
                    keyboardValue,
                    style: TextStyle(
                      fontSize: 24,
                    ),
                  ),
          ),
          Positioned.fill(
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: () {
                  _input(keyboardValue);
                },
              ),
            ),
          )
        ],
      );
    }
    return Container();
  }

  // 键盘
  Widget _keyboardBuilder() {
    int crossAxisCount = 3;
    double childAspectRatio = 2;

    return Container(
      height: Utils.width /
          crossAxisCount /
          childAspectRatio *
          (_keyboardList.length / crossAxisCount).ceil(),
      decoration: BoxDecoration(
        color: Color.fromRGBO(225, 225, 225, 1),
        border: Border(
          top: BorderSide(
            width: 1 * Utils.rpx,
            color: Color.fromRGBO(225, 225, 225, 1),
          ),
        ),
      ),
      child: HideScrollShadow(
        child: GridView.count(
          physics: NeverScrollableScrollPhysics(),
          crossAxisCount: crossAxisCount,
          mainAxisSpacing: 1 * Utils.rpx,
          crossAxisSpacing: 1 * Utils.rpx,
          padding: EdgeInsets.zero,
          childAspectRatio: childAspectRatio,
          children: List.generate(
            _keyboardList.length,
            _keyboardRect,
          ),
        ),
      ),
    );
  }

  // 键盘输入
  void _input(String value) {
    if (value == 'backspace' && _password.length > 0) {
      _password = _password.substring(0, _password.length - 1);
    } else if (value != 'backspace' && _password.length < _maxLength) {
      _password = _password + value;
    }

    List<String> _passwordArray = _password.split('');

    for (int i = 0; i < _maxLength; i++) {
      if (i < _passwordArray.length) {
        _passwordList[i] = _passwordArray[i];
      } else {
        _passwordList[i] = '';
      }
    }

    setState(() {});

    if (_password.length == _maxLength) {
      _final();
    }
  }

  // 完成
  void _final() {
    Navigator.pop(context, _password);
  }

  @override
  void initState() {
    super.initState();
    _passwordList = List<String>.filled(_maxLength, '');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.bottomCenter,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () => Navigator.pop(context),
            ),
          ),
          _titleBuilder(),
          _passwordRowBuilder(),
          _keyboardBuilder(),
        ],
      ),
    );
  }
}
